import Account
import BaseController
import Task

class TaskController extends BaseController {
	
	def index = { redirect(action: 'list', params: params)
	}
	
	def create = {
		def account = Account.get(session.account.id)
		def user = account.user
		render(view: 'create', model: [user: user])
		return
	}
	
	def save = {
		def account = Account.get(session.account.id)
		def task = new Task()
		task.properties = params  
		task.user = account.user
		
		if (task.save()) {
			flash.message = "Task ${task.name} saved."
			render(view: 'show', model: [task: task])
			return
		} else {
			flash.message = "Error saving task ${task.name}."
			render(view: 'create', model: [task: task])
			return
		}
	}
	
	def list = {
		def account = Account.get(session.account.id)
		def user = account.user
		def now = new Date()
		
		if (!params.max) params.max = 10
		if (!params.offset) params.offset = 0
		if (!params.sort) params.sort = "id"
		if (!params.order) params.order = "asc"
		
		def tasks = Task.withCriteria{
			eq("user", user)
			between('date', now, now + 1)
			
			maxResults(params.max?.toInteger())
			firstResult(params.offset?.toInteger())
			
			if (params.sort == 'priority') {
				priority {order('value', params.order)
				}
			} else {
				order(params.sort, params.order)
			}
		}
		
		flash.message = null;
		
		render(view: 'list', model: [tasks: tasks, user: user, total: tasks.size()])
	}
	
	def show = {
		def task = Task.get(params.id)
		render(view: 'show', model: [task: task])
	}
}
